<template>
	<view>
		<AppBar :autoBack="true" :title="title"></AppBar>
		<view class="container">
			<text class="titleH1">请输入验证码</text>
			<uv-gap height="10"></uv-gap>
			<text class="titleH2">验证码已发送至+86 138 8888 8888</text>
			<uv-gap height="30"></uv-gap>
			<view class="rowCenter">
				<uv-code-input :disabled-keyboard="true" v-model="code" :maxlength="6" :size="codeItemWidth"
					space="10"></uv-code-input>
			</view>
			<uv-gap height="30"></uv-gap>
			<view class="codeBtn rowEnd">
				<uv-code :seconds="seconds" @end="end" @start="start" ref="codeButton" @change="codeChange"></uv-code>
				<text class="tipsText" @click="getCode">{{tips}}</text>
			</view>
		</view>
		<uv-keyboard ref="keyboard" mode="number" :safe-area-inset-bottom="true" @change="change" :tooltip="false"
			:overlay="false" @backspace="backspace"></uv-keyboard>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		watch
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	const props = defineProps({
		title: {
			type: String,
			default: ""
		},
	})
	onLoad((option) => {
		if (option.title) {
			props.title = option.title
		}
		console.log('option:', option.title);
	})
	//键盘
	const keyboard = ref(null)
	//屏幕宽度
	const screenWidth = uni.getSystemInfoSync().windowWidth;
	//验证码输入框宽度
	const codeItemWidth = screenWidth / 6 - 14;
	onMounted(() => {
		//自动打开键盘
		keyboard.value.open();
	})
	const code = ref('')
	//键盘输入事件
	const change = (e) => {
		//拼接字符串
		if (code.value.length < 6) {
			code.value += e
		}
	}
	//键盘删除事件
	const backspace = (e) => {
		//删除字符串
		if (code.value.length > 0) {
			code.value = code.value.slice(0, -1)
		}
	}
	const checkCode = () => {
		//验证码校验
		console.log('验证码校验', code.value);
	}
	watch(
		() => code.value,
		(oldval, newval) => {
			if (newval && newval.length == 5) {
				checkCode();
			}
		}, {
			immediate: true,
			deep: true
		})

	//倒计时
	let timer = null
	let num = 60
	let seconds = ref(10)
	const codeButton = ref('')
	const tips = ref('获取验证码')
	const getCode = () => {
		if (codeButton.value.canGetCode) {
			// 模拟向后端请求验证码
			uni.showLoading({
				title: '正在获取验证码'
			})
			setTimeout(() => {
				uni.hideLoading();
				codeButton.value.start();
			}, 2000);
		} else {
			uni.showToast('倒计时结束后再发送');
		}
	}
	const codeChange = (text) => {
		tips.value = text;
	}
	const start = () => {
		uni.showToast('倒计时开始');
	}
	const end = () => {
		uni.showToast('倒计时结束');
	}
</script>

<style lang="scss" scoped>
	.codeBtn {
		padding: 0 20rpx;
	}
</style>